package com.org.redis.redisson;

import org.redisson.Redisson;
import org.redisson.api.*;

import java.util.concurrent.CountDownLatch;

public class RedissonDemo {

    /**
     * 基数估算算法
     */
    public static void hyperLogLog() {
        Redisson redisson = RedissonConfig.create1();
        RHyperLogLog<Integer> log = redisson.getHyperLogLog("log");
        for (int i = 1; i <= 20; i++) {
            log.add(i);
        }
        System.out.println(log.count());
    }

    /**
     * 整长型累加器
     */
    public static void longAddr(){
        Redisson redisson = RedissonConfig.create1();
        RLongAdder longaddr = redisson.getLongAdder("mylongaddr");
        longaddr.add(12L);
        longaddr.increment();
        longaddr.decrement();
        longaddr.decrement();
        System.out.println(longaddr.sum());
        //不使用的时候需要销毁对象
        longaddr.destroy();
    }

    /**
     * 限流器
     */
    public static void rateLimiter() {
        Redisson redisson = RedissonConfig.create1();
        //最大限流，每1s种产生10个令牌
        RRateLimiter limiter = redisson.getRateLimiter("limiter");
        limiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.SECONDS);

        CountDownLatch countDownLatch = new CountDownLatch(3);
        limiter.acquire(3);
        Thread thread = new Thread(() -> {
            limiter.acquire(2);
        });
        thread.start();
    }

    public static void main(String[] args) {
        longAddr();
    }
}
